package org.bee.service.impl;

import jakarta.annotation.PostConstruct;
import org.bee.mappers.BatchJobMapper;
import org.bee.model.BatchJob;
import org.bee.service.SysJobService;
import org.bee.util.ScheduleUtils;
import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysJobServiceImpl implements SysJobService {


    private final Scheduler scheduler;

    private final BatchJobMapper batchJobMapper;

    public SysJobServiceImpl(Scheduler scheduler, BatchJobMapper batchJobMapper) {
        this.scheduler = scheduler;
        this.batchJobMapper = batchJobMapper;
    }

    @PostConstruct
    public void init() throws SchedulerException {
        scheduler.clear();
        List<BatchJob> jobList = batchJobMapper.selectByExample(null);
        for (BatchJob job : jobList){
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
    }
    @Override
    public void run(BatchJob batchJob) throws SchedulerException {
        String id = batchJob.getId();
        String group = batchJob.getJobGroup();
        BatchJob properties = batchJobMapper.selectByPrimaryKey(id);
        // 参数
        JobDataMap dataMap = new JobDataMap();
        dataMap.put(ScheduleUtils.TASK_PROPERTIES, properties);
        JobKey jobKey = ScheduleUtils.getJobKey(id, group);
        if (scheduler.checkExists(jobKey)){
            scheduler.triggerJob(jobKey, dataMap);
        }
    }

    @Override
    public int pause(BatchJob job) throws SchedulerException {
        String id = job.getId();
        String group = job.getJobGroup();
        JobKey jobKey = ScheduleUtils.getJobKey(id, group);
        
        if (scheduler.checkExists(jobKey)) {
            scheduler.pauseJob(jobKey);
        }
        
        job.setStatus(false); // false表示暂停状态
        batchJobMapper.updateByPrimaryKey(job);
        return 1;
    }

    @Override
    public int resume(BatchJob job) throws SchedulerException {
        String id = job.getId();
        String group = job.getJobGroup();
        JobKey jobKey = ScheduleUtils.getJobKey(id, group);
        
        if (scheduler.checkExists(jobKey)) {
            scheduler.resumeJob(jobKey);
        }
        
        job.setStatus(true); // true表示运行状态
        batchJobMapper.updateByPrimaryKey(job);
        return 1;
    }

    @Override
    public void update(BatchJob batchJob) throws SchedulerException {
        String jobId = batchJob.getId();
        String jobGroup = batchJob.getJobGroup();
        // 判断是否存在
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
        if (scheduler.checkExists(jobKey))
        {
            // 防止创建时存在数据问题 先移除，然后在执行创建操作
            scheduler.deleteJob(jobKey);
        }
        ScheduleUtils.createScheduleJob(scheduler, batchJob);
    }
}
